package com.blue.gateway.aspect;

import com.alibaba.fastjson.JSON;
import com.blue.gateway.config.GatewayLogConfig;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author xiaoyiming
 * @date 2020/5/5 16:08
 * @depiction
 */
@Slf4j
@Aspect
@Order(1)
@Component
public class LogAspect {

    @Autowired
    private GatewayLogConfig gatewayLogConfig;

    @Around("execution(* com.blue..*.*(..)) && @annotation(com.blue.gateway.annotation.Log)")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Long startTime = System.currentTimeMillis();
        String className = point.getTarget().getClass().getName();
        String methodName = point.getSignature().getName();
        Object[] args = point.getArgs();
        try {
            Object resultValue = null;
            if (gatewayLogConfig.isShowAllLog() || gatewayLogConfig.isShowClientLog()) {
                log.info("[ACCESS] {}.{} args:{}", className, methodName, JSON.toJSONString(args));
                resultValue = point.proceed();
                log.info("[-->END] cost:{}ms,result:{}", System.currentTimeMillis() - startTime, JSON.toJSONString(resultValue));
            }
            return resultValue;
        } catch (Exception e) {
            log.error("", e);
        }
        return null;
    }

}
